from flask import Blueprint, render_template, flash, redirect, url_for, jsonify, request, current_app, send_from_directory
from sqlalchemy import and_
from sqlalchemy.exc import IntegrityError
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, jwt_required, create_refresh_token, jwt_refresh_token_required, get_jwt_identity, fresh_jwt_required
from datetime import datetime
from application.common.file_helper import *
from application.common.error_helper import *
from application.users.models import *

# 生成蓝图对象
api_product = Blueprint('api_product', __name__)

# 获取作品列表
@api_product.route('/avatar/<int:game_num>/<string:name>', methods=['GET'])
# @jwt_required
def get_avatar(game_num, name):
    # 查找对应的评选场次
    game = Game.query.get(game_num)
    if game is None:
        return jsonify({'code': NOT_GAME[0], 'message': NOT_GAME[1]})
    if game.status == 1:
        # json_data = request.get_json()
        # product_name = json_data['product_name']
        product_name = name
        print(product_name)
        product = Product.query.filter(Product.name == product_name).first()
        print(product)
        if product is None:
            return jsonify({'code': NAME_IS_NOT_EXIST[0], 'message': NAME_IS_NOT_EXIST[1]})
        filename = product.product_addr

        # 取到项目文件夹
        root_path = get_root_path(current_app)
        # UPLOAD_PATH = 'upload' 拼接绝对路径
        filepath = os.path.join(root_path, current_app.config['UPLOAD_PATH'])
        # 返回图片路径 + 文件名字
        print(send_from_directory(filepath, filename))
        return send_from_directory(filepath, filename)
    return jsonify({'code': GAME_IS_OVER[0], 'message': GAME_IS_OVER[1]})


# 给作品投票
@api_product.route('/avatar/<int:game_id>/<int:judge_id>', methods=['POST'])
# @jwt_required
def get_score(game_id, judge_id):
    json_data = request.get_json()
    product_name = json_data['product_name']
    game = Game.query.get(game_id)
    product = Product.query.filter_by(name=product_name).first()
    judge = Users.query.get(judge_id)
    # 判断评选场次是否在进行状态
    if game is None or game.status != 1:
        return jsonify({'code': GAME_NOT_RUN[0], 'message': GAME_NOT_RUN[1]})
    # 判断作品是否晋级到本次评选场次
    if product is None or product.status != 1:
        return jsonify({'code': PRODUCT_IS_ILLEGAL[0], 'message': PRODUCT_IS_ILLEGAL[1]})
    # 判断用户类型
    if judge is None or judge.user_type != 2:
        return jsonify({'code': NOT_JUDGE[0], 'message': NOT_JUDGE[1]})
    # 判断评委当场的剩余票数
    if judge.user_poll == 0:
        return jsonify({'code': POLL_IS_NONE[0], 'message': POLL_IS_NONE[1]})
    # 查询是否有原有纪录 根据输入的评选场次 id 和 作品id查询记录
    score = Score.query.filter(and_(Score.game_id == game_id, Score.product_id == product.id)).first()
    if score:
        score.score = score.score + 1
        db.session.add(score)
        db.session.commit()
    else:
        score = Score()
        score.game_id = game_id
        score.product_id = product.id
        score.score = 1
        db.session.add(score)
        db.session.commit()
    judge.user_poll = judge.user_poll - 1
    db.session.add(judge)
    db.session.commit()
    return jsonify({'code': POLL_SUCCESS[0], 'message': POLL_SUCCESS[1]})


# 结束当次评选
@api_product.route('/stop_game/<int:user_id>', methods=['POST'])
# @jwt_required
def stop_game(user_id):
    user = Users.query.get(user_id)
    if user is None:
        return jsonify({'code': ILLEGAL_ID[0], 'message': ILLEGAL_ID[1]})
    if user.user_type != 3:
        return jsonify({'code': ILLEGAL_USER[0], 'message': ILLEGAL_USER[1]})
    json_data = request.get_json()
    password = json_data['password']
    if check_password_hash(user.password,password):
        game_name = json_data['game_name']
        # 寻找对应场次
        game = Game.query.filter_by(name=game_name).first()
        if game is None:
            return jsonify({'code': NOT_GAME[0], 'message': NOT_GAME[1]})
        # 判断场次状态
        if not game.status:
            return jsonify({'code': STOP_GAME_ERROR[0], 'message': STOP_GAME_ERROR[1]})
        game.status = 0
        db.session.add(game)
        db.session.commit()
        return jsonify({'code': GAME_STOP_SUCCESS[0], 'message': GAME_STOP_SUCCESS[1], 'game_name': game_name})
    return jsonify({'code': JUDGE_PASSWORD_ERROR[0], 'message': JUDGE_PASSWORD_ERROR[1]})

# 开始新的评选场次
@api_product.route('/start_game/<int:user_id>', methods=['POST'])
def start_game(user_id):
    user = Users.query.get(user_id)
    if user is None:
        return jsonify({'code': ILLEGAL_ID[0], 'message': ILLEGAL_ID[1]})
    if user.user_type != 3:
        return jsonify({'code': ILLEGAL_USER[0], 'message': ILLEGAL_USER[1]})
    json_data = request.get_json()
    password = json_data['password']
    if check_password_hash(user.password, password):
        game_name = json_data['game_name']
        # 判断评选名字是否为空
        if len(game_name) == 0:
            return jsonify({'code': GAME_NAME_ERROR[0], 'message': GAME_NAME_ERROR[1]})
        # 防止管理员错误操作，未结束上场评选就开启新的评选
        games = Game.query.all()
        print(games)
        # 判断开启这次评选之前有没有其他场次，如果没有就跳过 if
        if len(games) != 0:
            # 上场没结束
            if games[-1].status:
                last_game_name = games[-1].name
                return jsonify({'code': 7001, 'message': '上场评选未结束，不能开始评选', 'last_game_name': last_game_name})
        # 名字重复
        game = Game.query.filter_by(name=game_name).first()
        if game is not None:
            return jsonify({'code': GAME_NAME_EXIST[0], 'message': GAME_NAME_EXIST[1], 'game_name': game_name})
        game = Game()
        game.name = game_name
        try:
            db.session.add(game)
            db.session.commit()
            # 重置评委的票数
            judges = Users.query.filter_by(user_type=2)
            for judge in judges:
                judge.user_poll = 5
                db.session.add(judge)
                db.session.commit()
            # 成功开启
            return jsonify({'code': GAME_START_SUCCESS[0], 'message': GAME_START_SUCCESS[1], 'game_name': game_name, 'game_id': game.id})
        except IntegrityError:
            return jsonify({'code': GAME_NAME_EXIST[0], 'message': GAME_NAME_EXIST[1], 'game_name': game_name})
    return jsonify({'code': JUDGE_PASSWORD_ERROR[0], 'message': JUDGE_PASSWORD_ERROR[1]})


# 查看作品的评选流程
@api_product.route('/product_flow', methods=['POST'])
# @jwt_required
def product_flow():
    json_data = request.get_json()
    product_name = json_data['product_name']
    # 查到输入对象
    product = Product.query.filter_by(name=product_name).first()
    if product:
        # 查询计分表中的该作品名字对应记录
        scores = Score.query.filter_by(product_id=product.id)
        flow_list = []
        for score in scores:
            flow_dict = {}
            # 获取记录的评选轮次名称
            game_name = Game.query.get(score.game_id).name
            # 获取票数
            product_score = score.score
            flow_dict['game_name'] = game_name
            flow_dict['product_score'] = '票数：%s' % product_score
            flow_list.append(flow_dict)
        if len(flow_list) == 0:
            return jsonify({'code': 9001, 'message': '没找到该作品的评选记录'})
        return jsonify({'code': 200, 'message': '成功', 'product_name': product_name, 'product_flow': flow_list})
    return jsonify({'code': NAME_IS_NOT_EXIST[0], 'message': NAME_IS_NOT_EXIST[1]})


# 获取当前比赛作品的名单
@api_product.route('/get_avatar_list', methods=['GET', 'POST'])
def get_avatar_list():
    products = Product.query.filter_by(status=1).all()
    if products is not None:
        name_list = []
        for product in products:
            avatar_dict = {}
            avatar_dict['name'] = product.name
            name_list.append(avatar_dict)
        return jsonify({'code': 200, 'message': '成功', 'data': name_list})
    return jsonify({'code': 10001, 'message': '没有作品晋级'})


# 决定淘汰几名
@api_product.route('/root', methods=['POST'])
def root():
    game = Game.query.filter_by(status=1).first()
    json_data = request.get_json()
    fire_num = int(json_data['fire_num'])
    # 本轮作品数
    product_num = len(Product.query.filter_by(status=1).all())
    if product_num <= fire_num or fire_num == 0:
        return jsonify({'code': PASS_ERROR[0], 'message': PASS_ERROR[1], 'product_num': '当前可晋级作品有%s件' % product_num})
    # 没有正在评选的轮次
    if game is None:
        name = json_data['name']
        password = json_data['password']
        user = Users.query.filter_by(name=name).first()
        if user:
            if check_password_hash(user.password, password):
                # 查询最后一轮评选的id
                last_game_id = Game.query.order_by(Game.id.desc()).first().id
                # 查询该场评选中的评选记录
                products = Score.query.filter_by(game_id=last_game_id).order_by(Score.score).all()
                # 判断淘汰数与本轮参赛作品数的关系
                if fire_num < len(products):
                    for index in range(fire_num):
                        # 取得淘汰作品的id
                        product_id = products[index].product_id
                        product = Product.query.get(product_id)
                        product.status = 0
                        db.session.add(products[index])
                        db.session.commit()
                        return jsonify({'code': 200, 'message': '成功'})
                return jsonify({'code': PASS_ERROR[0], 'message': '淘汰数应小于记录数', 'record_num': '当前记录数：%s' % len(products)})
            return jsonify({'code': JUDGE_PASSWORD_ERROR[0], 'message': JUDGE_PASSWORD_ERROR[1]})
        return jsonify({'code': ILLEGAL_ID[0], 'message': ILLEGAL_ID[1]})
    return jsonify({'code': GAME_IS_RUNNING[0], 'message': GAME_IS_RUNNING[1], 'game_name': game.name})